package io.finer.erp.jeecg.bas.service.impl;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;

import io.finer.erp.jeecg.bas.entity.BasMaterial;
import io.finer.erp.jeecg.bas.entity.BasMaterialCategory;
import io.finer.erp.jeecg.bas.entity.BasProductFormula;
import io.finer.erp.jeecg.bas.entity.ZrkDailyReportFq;
import io.finer.erp.jeecg.bas.entity.ZrkParameters;
import io.finer.erp.jeecg.bas.entity.ZrkQzOrder;
import io.finer.erp.jeecg.bas.entity.ZzDevice;
import io.finer.erp.jeecg.bas.entity.ZzShoporder;
import io.finer.erp.jeecg.bas.mapper.ZrkDailyReportFqMapper;
import io.finer.erp.jeecg.bas.service.IBasMaterialCategoryService;
import io.finer.erp.jeecg.bas.service.IBasMaterialService;
import io.finer.erp.jeecg.bas.service.IBasProductFormulaService;
import io.finer.erp.jeecg.bas.service.IZrkDailyReportFhService;
import io.finer.erp.jeecg.bas.service.IZrkDailyReportFqService;
import io.finer.erp.jeecg.bas.service.IZrkDailyReportQzService;
import io.finer.erp.jeecg.bas.service.IZrkMesFqParamService;
import io.finer.erp.jeecg.bas.service.IZrkParametersService;
import io.finer.erp.jeecg.bas.service.IZrkQzOrderService;
import io.finer.erp.jeecg.bas.service.IZzDeviceService;
import io.finer.erp.jeecg.bas.service.IZzShoporderService;
import io.finer.erp.jeecg.bas.vo.ZrkMesFqParamVO;
import io.finer.erp.jeecg.bas.vo.ZrkParametersVO;
import io.finer.erp.jeecg.stock.entity.StkIoBill;
import io.finer.erp.jeecg.stock.entity.StkIoBillEntry;
import io.finer.erp.jeecg.stock.mapper.StkIoBillEntryMapper;
import io.finer.erp.jeecg.stock.mapper.StkIoBillMapper;
import io.finer.erp.jeecg.stock.service.IStkIoBillEntryService;
import io.finer.erp.jeecg.stock.service.IStkIoBillService;

/**
 * @Description: 分切报表
 * @Author: jeecg-boot
 * @Date:   2021-08-12
 * @Version: V1.0
 */
@Service
public class ZrkDailyReportFqServiceImpl extends ServiceImpl<ZrkDailyReportFqMapper, ZrkDailyReportFq> implements IZrkDailyReportFqService {

	@Autowired
	private IZrkParametersService zrkParametersService;
	@Autowired
	private IZrkDailyReportFhService fhService;
	@Autowired
	private IZrkDailyReportFqService fqService;
	@Autowired
	private IZrkDailyReportQzService qzService;
	@Autowired
	private IZzShoporderService shoporderService;
	@Autowired
	private IZrkMesFqParamService zrkMesFqParamService;
	@Autowired
	private IStkIoBillService billService;
	@Autowired
	private IStkIoBillEntryService entryService;
	@Autowired
	private StkIoBillMapper billMapper;
	@Autowired
	private StkIoBillEntryMapper entryMapper;
	@Autowired
	private IZrkQzOrderService qzOrderService;
	@Autowired
	private IZzDeviceService deviceService;
	@Autowired
	private ISysBaseAPI sysBaseAPI;
	@Autowired
	private IBasMaterialCategoryService categoryService;
	@Autowired
	private IBasMaterialService materialService;
	@Autowired
	private IBasProductFormulaService formulaService;
	
	@Override
	public boolean updateReportFq(ZrkDailyReportFq zrkDailyReportFq) {
		// TODO Auto-generated method stub
		return this.updateById(zrkDailyReportFq);
	}
	
	@Override
	@Transactional
	public boolean saveReportFq(ZrkParametersVO zrkParametersVo) {
		// TODO Auto-generated method stub
		//查询主表数据
		ZrkQzOrder zrkQzOrder=qzOrderService.getById(zrkParametersVo.getProcessId());
		//分切--添加分切日报表
		if(StringUtils.equals("1300701063685087234", zrkQzOrder.getProcessId())) {
			ZrkDailyReportFq fq = new ZrkDailyReportFq();
			if(oConvertUtils.isNotEmpty(zrkQzOrder.getMachineId())) {
				ZzDevice device = deviceService.getById(zrkQzOrder.getMachineId());
				if(device!=null) {
					fq.setMachineId(device.getDeviceName());
				}
			}
			if(oConvertUtils.isNotEmpty(zrkQzOrder.getOperatorUsers())) {
				String[] userIds = StringUtils.split(zrkQzOrder.getOperatorUsers(), ",");
				List<LoginUser> userList = sysBaseAPI.queryAllUserByIds(userIds);
				if(userList!=null && userList.size()>0) {
					StringBuffer users = new StringBuffer();
					for(LoginUser user:userList) {
						users.append(user.getRealname());
						users.append(",");
					}
					if(users!=null && users.length()>0) {
						fq.setOperatorUsers(users.toString().substring(0, users.toString().length()-1));
					}
				}
			}
			BasMaterialCategory category = categoryService.getById(zrkQzOrder.getMaterialId());
			if(category!=null) {
				fq.setMaterialId(category.getFullname());
			}
			fq.setFqDate(new Date());//生产日期
			String[] orderIds =  StringUtils.split(zrkQzOrder.getOrderProcessId(), ",");
			List<String> orderList = Arrays.asList(orderIds);
			if(orderList!=null && orderList.size()>0) {
				List<ZzShoporder> shoporderList = shoporderService.listByIds(orderList);
				if(shoporderList!=null && shoporderList.size()>0) {
					StringBuffer orderNo = new StringBuffer();
					//若有合单关联的销售单可能有多条
					for(ZzShoporder shoporder:shoporderList) {
						if(!orderNo.toString().contains(shoporder.getOrderNo())) {
							orderNo.append(shoporder.getOrderNo());
							orderNo.append(",");
						}
					}
					if(orderNo!=null && orderNo.length()>0) {
						fq.setOrderNo(orderNo.substring(0, orderNo.length()-1));
					}
				}
			}
			StringBuffer width = new StringBuffer();
			StringBuffer length = new StringBuffer();
			Integer num = 0;//分切刀数
			BigDecimal sqSum = BigDecimal.ZERO; //分切总数量
			//查询分切参数
			List<ZrkMesFqParamVO> zrkMesFqParams=zrkMesFqParamService.selectParamBymesId(zrkQzOrder.getId());
			if(zrkMesFqParams !=null && zrkMesFqParams.size() > 0) {
				for(ZrkMesFqParamVO vo:zrkMesFqParams) {
					width.append(vo.getPartParam());
					width.append(",");
					length.append(vo.getHeight());
					length.append(",");
					if(vo.getQuantity() != null) {
						num = num + vo.getQuantity();
					}
					BigDecimal squares = BigDecimal.ZERO;//每个排刀方案分切总数量
					if(oConvertUtils.isNotEmpty(vo.getPartParam())) {
						String[] w = StringUtils.split(vo.getPartParam(), "=");
						if(w!=null&&w.length>0) {
							if(StringUtils.contains(vo.getPartParam(), "=")&&oConvertUtils.isNotEmpty(w[1])) {
								squares = new BigDecimal(w[1])
										.divide(new BigDecimal("100"), 2, BigDecimal.ROUND_HALF_UP)
										.multiply(new BigDecimal(vo.getHeight())).add(squares);
							}else {
								if(oConvertUtils.isNotEmpty(w[0])) {
									String[] wi = StringUtils.split(w[0], "+");
									if(wi!=null && wi.length>0) {
										for(String wid:wi) {
											String[] widt = StringUtils.split(wid, "*");
											if(widt!=null && widt.length>0) {
												if(oConvertUtils.isNotEmpty(widt[0]) && oConvertUtils.isNotEmpty(vo.getHeight())) {
													BigDecimal sq = new BigDecimal(widt[0])
															.divide(new BigDecimal("100"), 2, BigDecimal.ROUND_HALF_UP)
															.multiply(new BigDecimal(vo.getHeight()));
													if(widt.length>1 && oConvertUtils.isNotEmpty(widt[1])) {
														sq = sq.multiply(new BigDecimal(widt[1]));
													}
													squares = squares.add(sq);
												}
											}
										}
									}
								}
							}
						}
					}
					if(oConvertUtils.isNotEmpty(vo.getQuantity())) {
						sqSum = sqSum.add(squares.multiply(new BigDecimal(String.valueOf(vo.getQuantity()))));
					}
				}
				if(oConvertUtils.isNotEmpty(width)) 
					fq.setWidth(width.toString().substring(0, width.toString().length()-1));
				if(oConvertUtils.isNotEmpty(length)) 
					fq.setLength(length.toString().substring(0, length.toString().length()-1));
				
				fq.setKnifeNum(num);
				if(sqSum!=null) {
					fq.setSquare(sqSum);
				}
				fq.setAdjustNum(zrkMesFqParams.size());
			}
			String mesId = zrkQzOrder.getId();
			ZrkQzOrder order = new ZrkQzOrder();
			order = zrkQzOrder;
			while(!oConvertUtils.isEmpty(order.getParentId())) {
				order = qzOrderService.getById(order.getParentId());
				mesId = order.getId();
				if(StringUtils.equals("0", order.getParentId())) {
					break;
				}
			}
			List<String> materialids = billMapper.getMaterialIds(mesId, "2992");
			LambdaQueryWrapper<StkIoBillEntry> query = new LambdaQueryWrapper<>();
			query.in(StkIoBillEntry::getMaterialId, materialids);
			List<StkIoBillEntry> entryList = entryService.list(query);
			List<String> billidList = Lists.newArrayList();
			if(entryList!=null && entryList.size()>0) {
				for(StkIoBillEntry entry:entryList) {
					billidList.add(entry.getMid());
				}
				//根据出入库id列表查询分切生产入库信息
				LambdaQueryWrapper<StkIoBill> queryWrap = new LambdaQueryWrapper<>();
				queryWrap.in(StkIoBill::getId, billidList);
				queryWrap.eq(StkIoBill::getStockIoType, "1993");
				queryWrap.eq(StkIoBill::getBillProcStatus, "23");
				List<String> mesIdList = Lists.newArrayList();//记录分切mes单id
				List<StkIoBill> billList = billService.list(queryWrap);
				if(billList!=null && billList.size()>0) {
					for(StkIoBill bill:billList) {
						mesIdList.add(bill.getSourceId());
					}
					StringBuffer users = new StringBuffer();//上次分切此材料的分切员工
					List<ZrkQzOrder> qzOrderList = qzOrderService.listByIds(mesIdList);
					if(qzOrderList!=null && qzOrderList.size()>0) {
						for(ZrkQzOrder qzOrder:qzOrderList) {
							if(!StringUtils.equals(qzOrder.getId(), zrkQzOrder.getId())) {
								users.append(qzOrder.getOperatorUsers());
								users.append(",");
							}
						}
						if(oConvertUtils.isNotEmpty(users) && users.length()>0) {
							String userids = users.substring(0, users.toString().length()-1);
							String[] userIds = StringUtils.split(userids, ",");
							List<LoginUser> userList = sysBaseAPI.queryAllUserByIds(userIds);
							if(userList!=null && userList.size()>0) {
								StringBuffer userName = new StringBuffer();
								for(LoginUser user:userList) {
									userName.append(user.getRealname());
									userName.append(",");
								}
								if(userName!=null && userName.length()>0) {
									fq.setLastUser(userName.toString().substring(0, userName.toString().length()-1));
								}
							}
						}
					}
				}
				SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
				//查询该物料的复合信息
				queryWrap = new LambdaQueryWrapper<>();
				queryWrap.in(StkIoBill::getId, billidList);
				queryWrap.eq(StkIoBill::getStockIoType, "1992");
				queryWrap.eq(StkIoBill::getBillProcStatus, "23");
				queryWrap.orderByDesc(StkIoBill::getCreateTime);
				List<StkIoBill> fhBillList = billService.list(queryWrap);
				if(fhBillList!=null && fhBillList.size()>0) {
					StringBuffer ou = new StringBuffer();//复合操作员工
					StringBuffer glueMethod = new StringBuffer();
					StringBuffer volue = new StringBuffer();
					StringBuffer diverTime = new StringBuffer();
					List<String> mes = Lists.newArrayList();//复合mes单id
					List<String> midsList = Lists.newArrayList();
					List<String> pfList = Lists.newArrayList();
					for(StkIoBill bill:fhBillList) {
						if(!mes.contains(bill.getSourceId())) {
							mes.add(bill.getSourceId());
						}
						midsList.add(bill.getId());
						//获取复合mes单
						ZrkQzOrder qzOrder = qzOrderService.getById(bill.getSourceId());
						if(oConvertUtils.isNotEmpty(qzOrder.getFormulaId())) {
							pfList.add(qzOrder.getFormulaId());
						}
						if(oConvertUtils.isNotEmpty(qzOrder.getOperatorUsers())
								&& !ou.toString().contains(qzOrder.getOperatorUsers())) {
							ou.append(qzOrder.getOperatorUsers());
							ou.append(",");
						}
						List<ZrkParameters> parmList = zrkParametersService.selectByMainId(qzOrder.getId());
						if(parmList!=null && parmList.size()>0) {
							for(ZrkParameters parm:parmList) {
								//复合涂胶方式
								if(oConvertUtils.isNotEmpty(parm.getFhCoatingSurface())) {
									glueMethod.append(parm.getFhCoatingSurface());
									glueMethod.append(",");
								}
								//复合卷向
								if(oConvertUtils.isNotEmpty(parm.getFhVolume())) {
									volue.append(parm.getFhVolume());
									volue.append(",");
								}
							}
						}
						//复合生产日期
						if(oConvertUtils.isNotEmpty(qzOrder.getWoDeliverytime())) {
							String time = format.format(qzOrder.getWoDeliverytime());
							diverTime.append(time);
							diverTime.append(",");
						}
					}
					//获取复合配方
					if(pfList!=null && pfList.size()>0) {
						
						List<BasProductFormula> formulaList = formulaService.listByIds(pfList);
						if(formulaList!=null && formulaList.size()>0) {
							StringBuffer pf = new StringBuffer();
							for(BasProductFormula f:formulaList) {
								pf.append(f.getPfName());
								pf.append(",");
							}
							//品类-->配方
							if(pf!=null && pf.length()>0) {
								fq.setCategoryId(pf.toString().substring(0, pf.toString().length()-1));
							}
						}
					}
					if(ou!=null && ou.length()>0) {
						String ous = ou.toString().substring(0, ou.toString().length()-1);
						String[] userIds = StringUtils.split(ous, ",");
						List<LoginUser> userList = sysBaseAPI.queryAllUserByIds(userIds);
						if(userList!=null && userList.size()>0) {
							StringBuffer users = new StringBuffer();
							for(LoginUser user:userList) {
								users.append(user.getRealname());
								users.append(",");
							}
							if(users!=null && users.length()>0) {
								fq.setFhWorkNo(users.toString().substring(0, users.toString().length()-1));//复合机长工号->操作员
							}
						}
						
					}
					if(glueMethod!=null && glueMethod.length()>0) {
						fq.setFhGlueMethod(glueMethod.toString().substring(0, glueMethod.toString().length()-1));
					}
					if(volue!=null && volue.length()>0) {
						fq.setFhVolume(volue.toString().substring(0, volue.toString().length()-1));
					}
					if(diverTime!=null && diverTime.length()>0) {
						//复合生产日期
						fq.setFhProductDate(diverTime.toString().substring(0, diverTime.toString().length()-1));
					}
					if(midsList!=null && midsList.size()>0) {
						//复合生产入库物料详情
						List<StkIoBillEntry> entryLists = entryMapper.selectBatchByMainIdList(midsList);
						if(entryLists!=null && entryLists.size()>0) {
							StringBuffer barCode = new StringBuffer();//复合标签条码
							for(StkIoBillEntry entry:entryLists) {
								if(oConvertUtils.isNotEmpty(entry.getMaterialId())
										&& !barCode.toString().contains(entry.getMaterialId())) {
									barCode.append(entry.getMaterialId());
									barCode.append(",");
								}
							}
							if(barCode!=null && barCode.length()>0) {
								String bar = barCode.toString().substring(0, barCode.toString().length()-1);
								String[] maids = StringUtils.split(bar, ",");
								List<BasMaterial> materialList = materialService.listByIds(Arrays.asList(maids));
								if(materialList!=null && materialList.size()>0) {
									StringBuffer widths = new StringBuffer();
									StringBuffer lengths = new StringBuffer();
									StringBuffer codes = new StringBuffer();
									for(BasMaterial material:materialList) {
										codes.append(material.getCode());
										codes.append(",");
										if(oConvertUtils.isNotEmpty(material.getWidth())) {
											widths.append(material.getWidth());
											widths.append(",");
										}
										if(oConvertUtils.isNotEmpty(material.getLength())) {
											lengths.append(material.getLength());
											lengths.append(",");
										}
									}
									if(codes!=null && codes.length()>0) {
										fq.setFhBarcode(codes.toString().substring(0, codes.toString().length()-1));
									}
									if(widths!=null && widths.length()>0) {
										fq.setFhWidth(widths.toString().substring(0, widths.toString().length()-1));
									}
									if(lengths!=null && lengths.length()>0) {
										fq.setFhLength(lengths.toString().substring(0, lengths.toString().length()-1));
									}
								}
							}
						}
					}
					//复合生产出库所用物料
					queryWrap = new LambdaQueryWrapper<>();
					queryWrap.in(StkIoBill::getSourceId, mes);
					queryWrap.eq(StkIoBill::getStockIoType, "2991");
					queryWrap.eq(StkIoBill::getBillProcStatus, "23");
					List<StkIoBill> billsList = billService.list(queryWrap);
					if(billsList!=null && billsList.size()>0) {
						List<String> mids = Lists.newArrayList();
						for(StkIoBill io:billsList) {
							mids.add(io.getId());
						}
						List<StkIoBillEntry> bList = entryMapper.selectBatchByMainIdList(mids);
						if(bList!=null && bList.size()>0) {
							List<String> materialIdList = Lists.newArrayList();
							if(bList!=null && bList.size()>0) {
								for(StkIoBillEntry entry:bList) {
									materialIdList.add(entry.getMaterialId());
								}
								//外购材料来货日期
								List<StkIoBill> cgBillList = billMapper.selectBatchByMaterialIdList(materialIdList, "101");
								if(cgBillList!=null && cgBillList.size()>0) {
									StringBuffer cgTime = new StringBuffer();
									for(StkIoBill bill:cgBillList) {
										if(oConvertUtils.isNotEmpty(bill.getBillDate())) {
											cgTime.append(format.format(bill.getBillDate()));
											cgTime.append(",");
										}
									}
									if(cgTime!=null && cgTime.length()>0) {
										fq.setOutsideDate(cgTime.toString().substring(0, cgTime.toString().length()-1));
									}
								}
							}
						}
					}
				}else {
					//若查不到复合入库单，可能直接采购进行的分切
					queryWrap = new LambdaQueryWrapper<>();
					queryWrap.in(StkIoBill::getId, billidList);
					queryWrap.eq(StkIoBill::getStockIoType, "101");
					queryWrap.eq(StkIoBill::getBillProcStatus, "23");
					queryWrap.orderByDesc(StkIoBill::getCreateTime);
					List<StkIoBill> cgBillList = billService.list(queryWrap);
					if(cgBillList!=null && cgBillList.size()>0) {
						StringBuffer cgTime = new StringBuffer();
						for(StkIoBill bill:cgBillList) {
							if(oConvertUtils.isNotEmpty(bill.getBillDate())) {
								cgTime.append(format.format(bill.getBillDate()));
								cgTime.append(",");
							}
						}
						if(cgTime!=null && cgTime.length()>0) {
							//外购材料来货日期
							fq.setOutsideDate(cgTime.toString().substring(0, cgTime.toString().length()-1));
						}
					}
				}
				
			}
			return fqService.save(fq);
		}
		return false;
	}

}
